package com.sunlands.deskmate.message.handler.receiver.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunlands.deskmate.message.entity.Messages;
import com.sunlands.deskmate.message.handler.receiver.Receiver;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 *
 * @author anjunling@sunlands.com
 */
@Slf4j
@Component
public class PingMessageReceiver implements Receiver {

    @Override
    public void receive(Channel channel, Messages messages) {
        pong(channel);
    }

    private void pong(Channel channel) {
        String message = JSONObject.toJSONString(new Messages());
        ChannelFuture future = channel.writeAndFlush(new TextWebSocketFrame(message));
        future.addListener((ChannelFutureListener) channelFuture -> {
            if (!channelFuture.isSuccess()) {
                channelFuture.channel().writeAndFlush(new TextWebSocketFrame(message));
            }
        });
    }
}
